<script setup>
import { ref, reactive } from "vue";
import { formatTime } from "@/utils/format";
import { getUserDetail, addUser, updateUser } from "@/api/userManage";
import { upload } from "@/api/file";
import { ElMessage } from "element-plus";

// 抽屉显隐
const visibleDrawer = ref(false);

const emit = defineEmits(["success"]);

// 预览头像
const imageUrl = ref("");
// 保存选中的文件对象
const selectedFile = ref(null);

// 表单数据
const defaultForm = {
  username: "",
  password: "",
  roleType: 1,
  realName: "",
  phone: "",
  email: "",
  address: "",
  avatar: "",
};

const formModel = ref({ ...defaultForm });
const ruleFormRef = ref(null);

// 表单验证规则
const rules = reactive({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      min: 3,
      max: 20,
      message: "用户名长度在 5 到 20 个字符",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度在 6 到 20 个字符", trigger: "blur" },
  ],
  realName: [
    { min: 2, max: 10, message: "姓名长度在 2 到 10 个字符", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号格式",
      trigger: "blur",
    },
  ],
  email: [{ type: "email", message: "请输入正确的邮箱格式", trigger: "blur" }],
});

// 数据映射
const roleMap = [
  { label: "普通用户", value: 1 },
  { label: "农户", value: 2 },
];

const statusMap = [
  { label: "正常", value: 1 },
  { label: "禁用", value: 0 },
];

const handleOpen = async (data) => {
  visibleDrawer.value = true;
  if (data?.userId) {
    // 获取用户详情
    try {
      const res = await getUserDetail(data.userId);
      formModel.value = res.data.data;
    } catch (error) {
      ElMessage.error("获取用户详情失败");
      visibleDrawer.value = false;
    }
  } else {
    formModel.value = { ...defaultForm };
    // 重置表单验证状态
    if (ruleFormRef.value) {
      ruleFormRef.value.resetFields();
    }
  }
};

// 提交表单
const handleSubmit = async () => {
  await ruleFormRef.value.validate();
  if (selectedFile.value) {
    const formData = new FormData();
    formData.append("file", selectedFile.value);
    const res = await upload(formData);
    console.log(res);
    formModel.value.avatar = res.data.data;
  }
  if (formModel.value.userId) {
    const res = await updateUser(formModel.value);
    ElMessage({
      message: "修改成功",
      type: "success",
      plain: true,
    });
  } else {
    const res = await addUser(formModel.value);
    ElMessage({
      message: "添加成功",
      type: "success",
      plain: true,
    });
  }
  // 关闭抽屉
  handleCancel();
  // 触发父组件事件
  emit("success", formModel.value.userId ? "update" : "add");
};

// 取消按钮
const handleCancel = () => {
  visibleDrawer.value = false;
  imageUrl.value = "";
  selectedFile.value = null;
};

// 上传文件选择后的回调
const onUploadFile = (file) => {
  // 保存选择的文件
  selectedFile.value = file.raw;
  // 创建一个URL对象，将选择的文件转换为URL
  imageUrl.value = URL.createObjectURL(file.raw);
};

// 上传图片限制
const beforeAvatarUpload = (rawFile) => {
  const isJPG = rawFile.type === "image/jpeg" || rawFile.type === "image/png";
  if (!isJPG) {
    ElMessage.error("必须是jpg/png格式的图片");
    return false;
  }
  return true;
};

defineExpose({
  handleOpen,
});
</script>

<template>
  <!-- 抽屉 -->
  <el-drawer
    v-model="visibleDrawer"
    :title="formModel.userId ? '修改用户' : '添加用户'"
    direction="rtl"
    size="50%"
    @close="handleCancel"
  >
    <el-card style="max-width: 100%">
      <el-form
        ref="ruleFormRef"
        :model="formModel"
        :rules="rules"
        label-width="80px"
        status-icon
      >
        <el-form-item>
          <el-upload
            class="avatar-uploader"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="onUploadFile"
            :before-upload="beforeAvatarUpload"
            action="#"
          >
            <img
              v-if="formModel.avatar || imageUrl"
              :src="formModel.avatar || imageUrl"
              class="avatar"
              alt="用户头像"
            />
            <img v-else src="@/assets/avatar.jpg" width="150" alt="默认头像" />
          </el-upload>
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="formModel.username"
            :disabled="formModel.userId"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>

        <el-form-item label="密码" v-if="!formModel.userId" prop="password">
          <el-input
            v-model="formModel.password"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>

        <el-form-item label="类型">
          <el-select v-model="formModel.roleType" style="width: 200px">
            <template #prefix>
              <el-tag :type="formModel.roleType === 1 ? 'primary' : 'success'">
                {{ formModel.roleType === 1 ? "普通用户" : "农户" }}
              </el-tag>
            </template>
            <el-option
              v-for="item in roleMap"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="姓名" prop="realName">
          <el-input
            v-model="formModel.realName"
            placeholder="请输入真实姓名"
          ></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="formModel.phone"
            placeholder="请输入手机号"
            maxlength="11"
          ></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="formModel.email"
            placeholder="请输入邮箱"
          ></el-input>
        </el-form-item>

        <el-form-item label="地址">
          <el-input
            v-model="formModel.address"
            placeholder="请输入地址"
          ></el-input>
        </el-form-item>

        <el-form-item label="状态" v-if="formModel.userId">
          <el-select v-model="formModel.status" style="width: 150px">
            <template #prefix>
              <el-tag :type="formModel.status === 1 ? 'success' : 'danger'">
                {{ formModel.status === 1 ? "正常" : "禁用" }}
              </el-tag>
            </template>
            <el-option
              v-for="item in statusMap"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </el-drawer>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 150px;
      height: 150px;
      display: block;
      object-fit: cover; /* 图片自适应容器 */
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
  }
}
</style>
